//
//  SendEmailCodeViewController.swift
//  AESOLAR_IOS
//
//  Created by Mr.Wang on 2019/8/29.
//  Copyright © 2019 Mr.Wang. All rights reserved.
//

import UIKit
import RxSwift

class SendEmailCodeViewController: BaseUIViewController {
    
    let email: String
    
    let codeTextField = VerifyCodeTextField(count: 4)
    
    init(email: String) {
        self.email = email
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "请输入验证码".localized
        
        let topLabel = UILabel().config
            .font(.systemFont(ofSize: 35, weight: .bold))
            .text("验证码".localized)
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(40)
        }.view
        
        let text = String.init(format: "验证码已发送到邮箱 %@，请注意查收".localized, email)
        let attributeString = NSMutableAttributedString.init(string: text)
        attributeString.setParagraphSpace(8)
        attributeString.setTextColor(APPConfig.baseColor, text: email)
        
        let tipLabel = UILabel().config
            .textColor(#colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1))
            .numberOfLines(0)
            .font(.systemFont(ofSize: 14, weight: .medium))
            .attributedText(attributeString)
            .addTo(view)
            .makeConstraints { (make) in
                make.left.equalTo(20)
                make.top.equalTo(topLabel.snp.bottom).offset(20)
                make.centerX.equalToSuperview()
        }.view
        
        let codeButotn = UIButton().config
            .titleColor(APPConfig.baseColor)
            .font(UIFont.monospacedDigitSystemFont(ofSize: 15, weight: .medium))
            .title("发送验证码".localized)
            .addTo(view)
            .makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(tipLabel.snp.bottom).offset(20)
        }.view
        
        codeTextField.config
            .addTo(view)
            .makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(codeButotn.snp.bottom).offset(30)
                make.height.equalTo(45)
        }
        
        let buttonState = codeButotn.rx.tap.startWith(())
            .flatMap { [weak self] _ in
                return ApiManager.changeEmailSendCode(self?.email ?? "")
                    .request()
                    .errorWhenCodeNot200()
                    .trackingLoading("正在获取验证码".localized)
                    .flatMap { _ in
                        60.countdown({ String.init(format: "%d 秒后重新获取".localized, $0) }, resend: "重新发送验证码".localized)
                }.catchErrorJustReturn((title: "重新发送验证码".localized, isEnabled: false))
        }.share(replay: 1)
        
        buttonState.map{ $0.title }
            .bind(to: codeButotn.rx.title(for: .normal))
            .disposed(by: rx.disposeBag)
        
        buttonState.map{ $0.isEnabled }
            .bind(to: codeButotn.rx.isEnabled)
            .disposed(by: rx.disposeBag)
        
        let codeCheck = codeTextField.codeFinishInput.flatMap { [unowned self] in
            ApiManager.changeEmail(email: self.email, vcode: $0)
                .request()
                .trackingLoading()
                .errorWhenCodeNot200()
                .map{ _ in true }
                .catchErrorJustReturn(false)
        }.share(replay: 1)
        
        codeCheck.filter{ $0 }
            .post(.userInfoRefresh)
            .subscribe(onNext: { [weak self] (_) in
                let vc = ChangeEmailSuccessViewController()
                self?.navigationController?.pushTo(vc, remove: 2)
            }).disposed(by: rx.disposeBag)

        codeCheck.filter(!)
            .subscribe(onNext: { [weak self] (_) in
                self?.codeTextField.clearAll()
            }).disposed(by: rx.disposeBag)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        codeTextField.becomeFirstResponder()
    }
    
    override func navigationBarStyle() -> NavigationBarStyle {
        return .baseColor
    }
    
}
